#!/bin/bash -e

# Copyright 2022 Shadow Robot Company Ltd.
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the Free
# Software Foundation version 2 of the License.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
# more details.
#
# You should have received a copy of the GNU General Public License along
# with this program. If not, see <http://www.gnu.org/licenses/>.

request_firmware_version(){
  echo "polyscopeversion" | (exec 3<>/dev/tcp/$1/29999; cat >&3; cat <&3; exec 3<&-)
}

check_firmware_from_ip(){
  CONST_DRIVER_MINIMAL_REQUIRED_VERSION="5.1"
  responded=false
  export -f request_firmware_version
  current_dir=$(dirname "$0")
  good_firmware="${current_dir}/../config/known_good_firmware.txt"
  while read -r cmd; do
    if [[ $cmd =~ "URSoftware" ]]; then
      while read firmware; do
        if [[ $firmware != "" ]]; then
          if [[ $cmd =~ $firmware ]]; then
            echo -e "\e[32mUR version $cmd is supported by Shadow.\e[0m"
            responded=true
            break 2
          fi
        fi
      done <$good_firmware
        if [ "$(printf '%s\n' "$CONST_DRIVER_MINIMAL_REQUIRED_VERSION" "$cmd" | sort -V | head -n1)" = "$CONST_DRIVER_MINIMAL_REQUIRED_VERSION" ]; then 
            echo -e "\e[32mUR version $cmd has not been tested by Shadow but is supported by the driver.\e[0m"
        else
            echo -e "\e[33mUR version $cmd is NOT supported by Shadow. Use our software at your own risk.\e[0m"
        fi
      responded=true
      break
    fi
  done < <(timeout 2 bash -c "request_firmware_version $1")
  if [[ $responded == false ]]; then
    echo -e "\e[31mUR robot at $1 did not respond\e[0m"
  fi
}

source ~/projects/shadow_robot/base/devel/setup.bash 

arm_ips=$(echo $arm_ips | tr "_" "\n")
for arm_ip in $arm_ips ; do 
    echo "Checking firmware of arm at: $arm_ip"
    check_firmware_from_ip $arm_ip
done

